<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class Exchange extends Base
{
    protected $name = 'exchange';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function getAccountAttr($value)
    {
        return get_pay_way($value);
    }

    public function getTakeAccountAttr($value)
    {
        return get_pay_way($value);
    }

    public static function add($param, $user, $system): array
    {
        try {
            if (!$system['exchange_open']) {
                return ['code' => -1, 'msg' => '暂未开启转换功能'];
            }
            if ($param['account'] == $param['take_account']) {
                return ['code' => -1, 'msg' => '转出转入不能为同一账户'];
            }
            $account = $param['account'];

            if ($param['amount'] < $system['exchange_min']) {
                return ['code' => -1, 'msg' => '最低转换金额：' . $system['exchange_min']];
            }
            if ($system['exchange_bs']) {
                if ($param['amount'] % $system['exchange_bs'] != 0) {
                    return ['code' => -1, 'msg' => '转换倍数：' . $system['exchange_bs']];
                }
            }

            if ($user->assets->$account < $param['amount']) {
                return ['code' => -1, 'msg' => '余额不足'];
            }
            if ($user->pay_password != md5($param['pay_password'])) {
                return ['code' => -1, 'msg' => '支付密码错误'];
            }

            $cost = 0;
            if ($system['exchange_cost'] && $system['exchange_cost'] > 0) {
                $cost = round($param['amount'] * $system['exchange_cost'], 2);
            }

            parent::create([
                'uid'          => $user->id,
                'account'      => $param['account'],
                'take_account' => $param['take_account'],
                'cost'         => $cost,
                'amount'       => $param['amount'],
            ]);

            Target::Account()->basics($user->id, $param['account'], $param['amount'], $param['amount'], '转出', '-')->createNormal();
            Target::Account()->basics($user->id, $param['take_account'], $param['amount'] - $cost,$param['amount'] - $cost, '转入', '+')->createNormal();

            return ['code' => 1, 'msg' => '已转换'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}
